import { Scheduler } from "../libs/xviewer";
import { Ref, effect, onBeforeUnmount, reactive, watch } from "vue";

let scheduler = new Scheduler();

let time = null;
function frame() {
    let now = performance.now();
    if (time !== null) {
        let deltaTime = now - time;
        scheduler.update(deltaTime * 0.001);
    }
    time = now;
    requestAnimationFrame(frame);
}
frame();

let uid = 1;
const delayTarget = { uuid: "" + uid++ }

export function scheduleDelay(s: number) {
    return new Promise<any>(resolve => scheduler.schedule(delayTarget, resolve, s, 1));
}

export function unscheduleDelay() {
    scheduler.unscheduleAll(delayTarget);
}

export function useScheduler(
    callback: (dt: number) => void,
    deps: Ref[] = [],
    interval: number = 0,
    repeat: number = -1,
) {
    const target = reactive({ uuid: "" + uid++ });
    watch(deps,()=>{
        scheduler.schedule(target, callback, interval, repeat);   
    },{immediate:true})
    onBeforeUnmount(() => {
        scheduler.unshedule(target, callback)
    })
}